package itpenguin.train.common;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.transit.realtime.GtfsRealtime.FeedEntity;
import com.google.transit.realtime.GtfsRealtime.FeedMessage;
import com.google.transit.realtime.GtfsRealtime.VehiclePosition;

public abstract class GtfsRealTimeFeed implements TrainFeed {

    protected List<Train> fetchFeed(URL url) throws IOException {
        
    	List<Train> positions = new ArrayList<Train>();
    	FeedMessage fm = FeedMessage.parseFrom(url.openStream());
        
        for (FeedEntity entity : fm.getEntityList()) {
            if (entity.hasVehicle()) {
                VehiclePosition vp = entity.getVehicle();
                if (filter(vp)) {
	                Position position = new Position(vp.getPosition().getLatitude(), vp.getPosition().getLongitude());
	                Train tp = new Train(position.getLatitude(), position.getLongitude(), vp.getCurrentStatus()
	                        ,vp.getVehicle().getId(), vp.getTrip().getTripId(), vp.getTrip().getRouteId(),
	                        new Date(vp.getTimestamp() * 1000));
	                positions.add(tp);
                }
            }
        }
        
        return positions;
    }
    
    protected boolean filter(VehiclePosition vp) {
    	return true;
    }
}
